package me.nareshkumarrao.IRCraft;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.User;

public class IRCraft extends JavaPlugin{
	
	
	
	Logger log = Logger.getLogger("MineCraft");
	IRCraftBot bot;
	private final EventPlayerListener playerListener = new EventPlayerListener(this);
	
	public Configuration config;
	
	public String channel;
	public String network;
	public String nick;
	public Boolean isVerbose;
	public int port;
	public String password;
	public CommandSender CommSender;

	
	public void onEnable()
	{
		PluginManager pm = getServer().getPluginManager();
		pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Normal, this);
		pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
		pm.registerEvent(Event.Type.PLAYER_BED_ENTER, playerListener, Priority.Normal, this);
		pm.registerEvent(Event.Type.PLAYER_BED_LEAVE, playerListener, Priority.Normal, this);
		pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Normal, this);

		File chkConfig = new File("plugins/IRCraft/config.yml");
		if(!chkConfig.exists())
		{
			log.warning("[IRCraft]: Config Not Found! Creating New Config.");
		}
		config = getConfiguration();
		channel = config.getString("channel","#IRCraft");
		network = config.getString("network","irc.mozilla.org");
		nick = config.getString("nick", "MineCraft");
		isVerbose = config.getBoolean("verboseMode", false);
		port = config.getInt("port", 6667);
		password = config.getString("password", "");
		config.setHeader("#Thank You For Using IRCraft.\n#\n#What these configs mean:\n#nick: The name that you want the IRC bot to appear as.\n#channel: The channel that you want the bot to join.\n#server: The server that you want the bot to join.\n#\n#Nareshkumar Rao - inaresh.online@gmail.com");
		config.save();
		
		bot = new IRCraftBot(nick);
		
		log.info("[IRCraft]: Connecting to "+network+" with nick: "+nick);
		
		bot.setVerbose(isVerbose);
		try {
			bot.connect(network);
		} catch (NickAlreadyInUseException e) {
			log.info("IRCRaft: The nick is in use.");
		} catch (IOException e) {
			//Nothing
		} catch (IrcException e) {
			//Nothing
		}
		if(password!="")
		{
			bot.identify(password);
		}
		bot.joinChannel(channel);
		
		
		
		log.info("[IRCraft]: Version 2.0 Enabled Successfully");
		log.info("[IRCraft]: Developed by Nareshkumar Rao");
		log.info("[IRCraft]: For MineCraft Beta 1.7.3");
		log.info("[IRCraft]: And Bukkit 1060");
	}
	

	public void onDisable()
	{
		log.info("[IRCraft]: Disabled Successfully");
	}
	

	public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
	{
		String comm = cmd.getName();

			if(comm.equalsIgnoreCase("ircjoin"))
			{
				if(args.length<1)
				{
					return false;
				}
				bot.joinChannel(args[0]);
				
				Bukkit.getServer().broadcastMessage("IRCraft: Joined channel "+args[0]);
				return true;
			}
			if(comm.equalsIgnoreCase("irclist"))
			{
				if(args.length<1)
				{
					return false;
				}
				sender.sendMessage("IRCraft: Users in "+args[0]);
				User[] users = bot.getUsers(args[0]);
				for(int i = 0; i < users.length; i++)
				{
					sender.sendMessage(users[i].getNick());
				}
				
				return true;
			}
			if(comm.equalsIgnoreCase("ircchanlist"))
			{
				sender.sendMessage("IRCraft: Listing Channels");
				CommSender = sender;
				bot.getInstance(this);
				bot.listChannels();
				
				return true;
			}
			if(comm.equalsIgnoreCase("ircleave"))
			{
				if(args.length<1)
				{
					return false;
				}
				bot.partChannel(args[0]);
				
				Bukkit.getServer().broadcastMessage("IRCraft: Left channel "+args[0]);
				return true;
			}
			if(comm.equalsIgnoreCase("ircload"))
			{
				config = getConfiguration();
				channel = config.getString("channel","#IRCraft");
				network = config.getString("network","irc.mozilla.org");
				nick = config.getString("nick", "MineCraft");
				isVerbose = config.getBoolean("verboseMode", false);
				port = config.getInt("port", 6667);
				password = config.getString("password", "");
				config.setHeader("#Thank You For Using IRCraft.\n#\n#What these configs mean:\n#nick: The name that you want the IRC bot to appear as.\n#channel: The channel that you want the bot to join.\n#server: The server that you want the bot to join.\n#\n#Nareshkumar Rao - inaresh.online@gmail.com");
				config.save();
				
				Bukkit.getServer().broadcastMessage("IRCraft: Config Reloaded.");
				
				bot.disconnect();
				Bukkit.getServer().broadcastMessage("IRCraft: Disconnected. Waiting 10 Seconds to reconnect");
				this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
					
				    public void run() {
				    	Bukkit.getServer().broadcastMessage("IRCraft: Connecting to "+network);
						try {
							bot.connect(network, port);
						} catch (NickAlreadyInUseException e) {
							log.info("IRCRaft: The nick is in use.");
							
						} catch (IOException e) {
							//Nothing
						} catch (IrcException e) {
							//Nothing
						}
						if(password!="")
						{
							bot.identify(password);
						}
						bot.joinChannel(channel);
						
						Bukkit.getServer().broadcastMessage("IRCraft: Reconnected to "+network);

				    }
				}, 200L);
				
				return true;
			}
			if(comm.equalsIgnoreCase("ircdc"))
			{
				bot.disconnect();
				
				Bukkit.getServer().broadcastMessage("IRCraft: Disconnected from "+network);
				return true;
			}
			if(comm.equalsIgnoreCase("ircrc"))
			{	
				if(args.length>0)
				{
					network=args[0];
				}
				bot.disconnect();
				Bukkit.getServer().broadcastMessage("IRCraft: Disconnected. Waiting 10 Seconds to reconnect");
				this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {

				    public void run() {
				    	Bukkit.getServer().broadcastMessage("IRCraft: Connecting to "+network);
						try {
							bot.connect(network,port);
						} catch (NickAlreadyInUseException e) {
							log.info("IRCRaft: The nick is in use.");
							
						} catch (IOException e) {
							//Nothing
						} catch (IrcException e) {
							//Nothing
						}
						if(password!="")
						{
							bot.identify(password);
						}
						bot.joinChannel(channel);
						
						Bukkit.getServer().broadcastMessage("IRCraft: Reconnected to "+network);

				    }
				}, 200L);
				
				return true;
			}
			if(comm.equalsIgnoreCase("ircraft") || comm.equalsIgnoreCase("irc"))
			{
				
				sender.sendMessage("IRCraft Help");
				sender.sendMessage("/ircjoin <channel> : Join an IRC channel");
				sender.sendMessage("/ircleave <channel> : Leave an IRC channel");
				sender.sendMessage("/ircload : Reload the config.yml file and reconnect");
				sender.sendMessage("/ircdc : Disconnect from the network");
				sender.sendMessage("/ircrc [network] : Connect to a network");
				sender.sendMessage("/irclist <channel> : List the players in a specified channel.");
				sender.sendMessage("/ircchanlist : List all channels in network.");
				
				return true;
			}
			

		return false;
	}
}
